package com.whz.mlc.factory;

import com.google.common.collect.Maps;
import com.whz.generic.spring.SpringUtils;
import com.whz.mlc.cache.local.MlcLocalCacheBean;
import com.whz.mlc.cache.second.MlcSecondCacheBean;
import com.whz.mlc.exception.BeanNotFoundException;
import lombok.experimental.UtilityClass;

import java.util.Map;

/**
 * @author whz
 * 2021/8/30
 */
@UtilityClass
public class MlcCacheHolder {
    private final static Map<String, MlcSecondCacheBean> MLC_SECOND_CACHE_MAP = Maps.newConcurrentMap();
    private final static Map<String, MlcLocalCacheBean> MLC_CACHE_MAP = Maps.newConcurrentMap();

    public boolean hasSecondCache(final String cacheName) {
        return MLC_SECOND_CACHE_MAP.containsKey(cacheName);
    }

    public void putSecondCache(final String cacheName, final MlcSecondCacheBean tmcSecondCache) {
        MLC_SECOND_CACHE_MAP.put(cacheName, tmcSecondCache);
    }

    public MlcSecondCacheBean getSecondCache(final String cacheName) {
        if (!hasSecondCache(cacheName)) {
            return SpringUtils.getBean(MlcCacheFactory.class)
                              .map(factory -> factory.getSecondCache(cacheName))
                              .orElseThrow(() -> new BeanNotFoundException(
                                      "未找到cacheName:" + cacheName + "的TmcSecondCache."));
        }
        return MLC_SECOND_CACHE_MAP.get(cacheName);
    }


    public boolean hasLocalCache(final String cacheName) {
        return MLC_CACHE_MAP.containsKey(cacheName);
    }

    public void putLocalCache(final String cacheName, final MlcLocalCacheBean tmcSecondCache) {
        MLC_CACHE_MAP.put(cacheName, tmcSecondCache);
    }

    public MlcLocalCacheBean getLocalCache(final String cacheName) {
        if (!hasLocalCache(cacheName)) {
            return SpringUtils.getBean(MlcCacheFactory.class)
                              .map(factory -> factory.getLocalCache(cacheName))
                              .orElseThrow(() -> new BeanNotFoundException(
                                      "未找到cacheName:'" + cacheName + "'的CacheBean"));
        }
        return MLC_CACHE_MAP.get(cacheName);
    }
}